package com.zang.netty.bio;

import com.zang.netty.model.enums.SocketEnum;

import java.io.*;
import java.net.Socket;

/**
 * 自动阻塞
 * @author Zhang Qiang
 * @Date 2019/7/18 16:51
 */
public class TimeClient {

    public static void main(String[] args) {

        int port = SocketEnum.PORT.getNum();
        String ip = SocketEnum.LOCALHOST.getStr();

        System.out.println((args == null)?" args is null " : " args.length:" + args.length);

        // args != null && args.length > 0 保证健壮性，but！ 测试的时候不需要参数，所以args为0
        if (args != null && args.length == 0){
            System.out.println(" start send");
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e){
                // 采用默认值
            } catch (ArrayIndexOutOfBoundsException a){

            }
            Socket socket = null;
            BufferedReader in = null;
            PrintWriter out = null;
            try {
                socket = new Socket(ip,port);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new PrintWriter(socket.getOutputStream(), true);


                // 通过获取控制台信息发送
                System.out.println("请输入信息：");
                BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
                String br = bf.readLine();
                if ("QUERY TIME ORDER".equals(br) || "qro".equals(br)){
                    // out msg
                    out.println("QUERY TIME ORDER");
                    System.out.println("send 'QUERY TIME ORDER'");
                }else {
                    out.println(br);
                    System.out.println("send " + br);
                }

                //获取返回信息
                String resp = in.readLine();
                System.out.println("Now is : " + resp);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("catch Exception :" + e.getLocalizedMessage());
            }finally {
                if (null != in){
                    try {
                        in.close();
                    }catch (IOException el){
                        el.printStackTrace();
                    }
                }
                if (null != out){
                    out.close();
                    out = null;
                }
                if (null != socket){
                    try {
                        socket.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    socket = null;
                }
            }

        }
    }

}
